#include <stdio.h>
#include <time.h>
#include <memory.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include <io.h>
#include <fcntl.h>
#endif
int main(int argc, char *argv[])
{
	const size_t package_size = 1024*1024;
	char * array = (char *)malloc(package_size);
	unsigned long long * header = (unsigned long long *)array;
	unsigned long long * length = (unsigned long long *)(array+sizeof(unsigned long long));
	unsigned long long totalsz = 0;
	clock_t start_clk = 0, end_clk = 0, total_clk = 0;
	int produce = 0, consume = 0;
	int i = 0;
	for (int i=1;i<argc;++i)
	{
		//-p means produce
		if (strstr(argv[i],"p"))
			produce = 1;
		if (strstr(argv[i],"c"))
			consume = 1;
	}
	if (produce==0 && consume==0)
	{
		fprintf(stderr,"Usage: %s <[-c][-p]>\n",argv[0]);
		return 0;
	}
#ifdef _WIN32
	_setmode(_fileno(stdout), O_BINARY);
	_setmode(_fileno(stdin), O_BINARY);
#endif

	start_clk = clock();
	if (produce==1 && consume==0)
	{
		long long lz = 0;
		while (++lz < 10000)
		{
			*header = lz;
			*length = package_size-sizeof(unsigned long long)*2;
			//Produce
			fwrite((char *)header,1,*length + sizeof(unsigned long long)*2,stdout);
			fflush(stdout);
			totalsz += *length + sizeof(unsigned long long)*2;
		}
		*header = lz;
		*length = 0;
		fwrite((char *)header,1,sizeof(unsigned long long)*2,stdout);
		fflush(stdout);
		totalsz += sizeof(unsigned long long)*2;
	}
	else if (produce==0 && consume==1)
	{
		fread((char *)header,2,sizeof(unsigned long long),stdin);
		while (*length)
		{
			//Consume
			fread(((char *)header)+sizeof(unsigned long long)*2,1,*length,stdin);
			totalsz += *length + sizeof(unsigned long long)*2;
			fread((char *)header,2,sizeof(unsigned long long),stdin);
		}
		totalsz += sizeof(unsigned long long)*2;
	}
	else
	{
		fread((char *)header,2,sizeof(unsigned long long),stdin);
		while (*length)
		{
			//Consume
			fread(((char *)header)+sizeof(unsigned long long)*2,1,*length,stdin);
			//Produce
			fwrite((char *)header,1,*length + sizeof(unsigned long long)*2,stdout);
			fflush(stdout);
			totalsz += *length + sizeof(unsigned long long)*2;
			fread((char *)header,2,sizeof(unsigned long long),stdin);
		}
		fwrite((char *)header,1,*length + sizeof(unsigned long long)*2,stdout);
		fflush(stdout);
		totalsz += sizeof(unsigned long long)*2;

	}

	free(array);
	end_clk = clock();

	total_clk = end_clk - start_clk;

	fprintf(stderr,"%lld Bytes %s%s\n\t%.3lf MB/s(%.2lf Gbits/s)\n\tRX(sc16) %.2lf MHz\n\tRTX(sc16) %.2lf MHz.\n",
			totalsz,
			(consume?"Consumed ":""),
			(produce?"Produced ":""),
			totalsz *1.0/1024/1024/(total_clk*1.0/CLOCKS_PER_SEC),
			totalsz *8.0/1024/1024/1024/(total_clk*1.0/CLOCKS_PER_SEC),
			totalsz *1.0/1024/1024/(total_clk*1.0/CLOCKS_PER_SEC)/4.0,
			totalsz *1.0/1024/1024/(total_clk*1.0/CLOCKS_PER_SEC)/8.0
			);
	return 0;
}
